<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\BaseController;
use Common\ORG\Page,Common\ORG\AttUpload,Common\ORG\Excel;
/**
 * 客户池管理
 *
 */
class CustomerController extends BaseController {
    private $m_cacheSearch = array('product'=>array(),'user'=>array(),'sector'=>array());
    private $m_parseError = array();
    private $m_payExcelKey = array('序列' => 'order','打款日期'=>'pay_time','打款人名或微信昵称名'=>'pay_name','客户'=>'customer_name','金额'=>'mount',
                                    '到款方式'=>'pay_way','业务员'=>'sales_person','经理'=>'sales_manager','团队'=>'team','备注'=>'remark',
                                    '对账结果（财务填写）'=>'audit_res','是否违规'=>'is_weigui','订单号'=>'order_number');
    private $m_customerExcelKey = array('编号'=>'pay_order','客户姓名'=>'customer_name','电话'=>'phone','产品类型'=>'product','金额'=>'mount',
                                            '服务期限'=>'service_time','资金量'=>'customer_mount','问卷回执'=>'survey_code','跟踪人'=>'sales_person','业务经理'=>'sales_manager',
                                            '合同开始时间'=>'contract_time','合同定价'=>'contract_mount','回访时间'=>'revisit_time','回访类别'=>'revisit_res',
                                            '备注'=>'remark','微信号' =>'weixin_id','回访摘要'=>'revisit_remark');

	//客户池首页
	public function index()
    {
        $export = I('get.export', '', 'intval');
        $psize    = I('get.psize', '','intval');
        $p        = I('get.p', '', 'intval');
        $template_export = I('get.template_export', 0, 'intval');
        $psize = !$psize||$psize>100 ?  $this->m_psize:$psize;
        if ($template_export){
            $this->_importTemplate();
        }

        $MCustmer = D("Admin/Customer");
        $MPay = D('Admin/Pays');
        $customer = I('get.customer', '','trim');
        $sales = I('get.sales','', 'trim');
        $start_time = I('get.start_time','', 'trim');
        $end_time = I('get.end_time','', 'trim');
        $audit = I('get.audit', -1, 'intval');
        $wheres = array();
        $wheres['_string'] = '1=1';
        if( $audit != -1 )
            $wheres['c.state'] = array('eq', $audit );
        if( $start_time && $end_time ){
            $s_tm = strtotime( $start_time );
            $s_tm = strtotime("-1 day", $s_tm);
            $e_tm = strtotime( $end_time );
            $wheres['c.create_time'] = array('between', array(date('Y-m-d 23:59:59', $s_tm), date('Y-m-d 23:59:59', $e_tm)) );
        }
        else if( $start_time ){
            $tm = strtotime( $start_time );
            $tm = strtotime("-1 day", $tm);
            $wheres['c.create_time'] = array('gt', date('Y-m-d 23:59:59', $tm ) );
        }
        else if( $end_time ){
            $tm = strtotime( $end_time );
            $wheres['c.create_time'] = array('lt', date('Y-m-d 23:59:59', $tm ) );
        }
        if( $sales ){
            $MUser = D('Admin/User');
            $whereu = array();
            $whereu['nickname'] = array('like', '%'.$sales.'%');
            $_arr_users = $MUser->field('user_id')->where( $whereu )->select();
            $arr_users = array();
            foreach( $_arr_users as $vau ){
                $arr_users[] = $vau['user_id'];
            }
            if( !$arr_users) $arr_users[] = 0;
            $wheres['c.sales_person'] = array('in', $arr_users );
        }
        if( $customer ){
            if( preg_match('#^\d{4,13}$#', $customer )){
                $MPhoneBook = D('Admin/CustomerPhonebook');
                $wherep = array();
                $wherep['book_phone'] = array('like','%'.$customer.'%');
                $_arr_phones = $MPhoneBook->field("customer_id")->where( $wherep )->select();
                $arr_phones = array();
                foreach ($_arr_phones as $kp => $vp) {
                    $arr_phones[] = $vp['customer_id'];
                }
                if( !$arr_phones )
                    $arr_phones[] = 0;
                $wheres['c.customer_id'] = array('in', $arr_phones );
            }
            else if (substr($customer, 0,2) == 'AA') {
                $wheres['c.customer_code'] = array('like', $customer.'%');
            }
            else{
                $wheres['c.nickname'] = array('like', '%'.$customer.'%');
            }
        }
        //导出Excel
        if ($export) {
            $ServiceUser = D("Admin/User","Service","Admin");
            $r_export =$ServiceUser->authWithKey( $this->m_user['user_id'], 'CUSTOMER_EXPORT');  //基本信息导出权限
            $r_export_vital =$ServiceUser->authWithKey( $this->m_user['user_id'], 'CUSTOMER_DATA_VITAL');   //敏感信息导出权限
            if (!$r_export['rcode'] && !$r_export_vital['rcode'] ) {
                $res['msg'] = "无权导出数据";
            }else{
                if($r_export_vital['rcode']){
                    $header = array('remark'=>'特殊备注','state'=>'状态','nickname'=>'客户姓名','sex'=>'性别','protect_time'=>'服务时间',
                        'phone'=>'电话','weixin_id'=>'微信号','qq'=>'QQ','email'=>'邮箱','mount'=>'资金量(万)','sales'=>'跟踪人',
                        'sales_manager'=>'业务经理','sales_sub_company'=>'团队','create_time'=>'首次服务时间');
                }else if($r_export['rcode']){
                    $header = array('remark'=>'特殊备注','state'=>'状态','nickname'=>'客户姓名','sex'=>'性别','protect_time'=>'服务时间',
                        'mount'=>'资金量(万)','sales'=>'跟踪人','sales_manager'=>'业务经理','sales_sub_company'=>'团队','create_time'=>'首次服务时间');
                }
                $list = $MCustmer->alias("c")
                                ->field("c.nickname,c.sex,c.phone,c.weixin_id,c.qq,c.email,c.mount,c.state,c.create_time,c.location,c.remark,
                                        c.state,c.customer_id,c.protect_time,u.nickname as sales_name,s.name as source_name,
                                        m.nickname as manager_name,sec.sector_name as sub_company
                                        ")
                                ->join("LEFT JOIN user  u on u.user_id=c.sales_person")
                                ->join("LEFT JOIN user m on m.user_id=c.sales_manager")
                                ->join("LEFT JOIN source s on s.source_id=c.source_id")
                                ->join("LEFT JOIN sector sec on sec.sector_id=c.sales_sub_company")
                                ->where( $wheres )
                                ->order("c.create_time desc")
                                ->select();
                $item = array();
                $MExcel= new Excel();
                $Sheet = new \Common\ORG\Sheet("客户数据");
                $Sheet->setColumn( array_values( $header) );
                foreach ($list as $vc ) {
                    $sex = intval( $vc['sex'] );
                    $item['remark'] = $vc['remark'];
                    $state = intval( $vc['state'] );
                    $item['state'] = $state==0 ? '待审核':( $state==1 ? '正常':( $state==2 ? '禁止登录' : '被合并') );
                    $item['nickname'] = $vc['nickname'];
                    $item['sex'] = 0==$sex? '':( 1==$sex ? '男':'女');
                    $item['protect_time'] = substr($vc['protect_time'],0,10);
                    if($r_export_vital['rcode']){
                        $item['phone'] = $vc['phone'] ? ' '.$vc['phone']:'';
                        $item['weixin_id'] = $vc['weixin_id'] ? ' '.$vc['weixin_id']:'';
                        $item['qq'] = $vc['qq'] ? ' '.$vc['qq']:'';
                        $item['email'] = $vc['email'] ? ' '.$vc['email']:'';
                    }
                    $item['mount'] = $vc['mount'];
                    $item['sales'] = $vc['sales_name'];
                    $item['sales_manager'] = $vc['manager_name'];
                    $item['sales_sub_company'] = $vc['sub_company'];
                    $item['create_time'] = $vc['create_time'];
                    $Sheet->addRow( array_values($item) );
                }

                $MExcel->add_sheet( $Sheet );
                $exportRet = $MExcel->export_sheet("客户数据");
                if( $exportRet['rcode'] ){
                    $res['rcode'] = 1;
                    $res['data'] = $exportRet['data'];
                    $res['msg'] = 'OK';
                }
                else
                    $res['msg'] = $exportRet['msg'];
            }

        }
        else {
            $count = $MCustmer->alias("c")->where( $wheres )->count();
            $Page = new Page( $count, $psize );
            $list = $MCustmer->alias("c")
                             ->field("c.nickname,c.mount,c.create_time,c.location,c.remark,c.customer_code,
                                    c.state,c.phone,c.customer_id,u.nickname as sales_name,s.name as source_name,
                                    m.nickname as manager_name,sec.sector_name as sub_company")
                             ->join("LEFT JOIN user  u on u.user_id=c.sales_person")
                             ->join("LEFT JOIN user m on m.user_id=c.sales_manager")
                             ->join("LEFT JOIN sector sec on sec.sector_id=c.sales_sub_company")
                             ->join("LEFT JOIN source s on s.source_id=c.source_id")
                             ->where( $wheres )
                             ->limit( $Page->firstRow.','.$Page->listRows  )
                             ->order("c.create_time desc")
                             ->select();
            $wherep = array();
            $wherep['record_status'] = array('eq', 1);//没有作废
            $wherep['audit_res'] = array('eq', 1);//审核成功
            foreach ($list as &$vk) {
                $wherep['customer_id'] = array('eq', $vk['customer_id']);
                $vk['phone'] = phone_mask($vk['phone']);
                $vk['pay'] = $MPay->where( $wherep )->sum('pay_mount');
                if (!$vk['pay'])
                    $vk['pay'] = 0;
            }
            $res['rcode'] = 1;
            $res['data']  = $list;
            $res['page']    =  $Page->getTotalPages();
            $res['p']       = $Page->nowPage;
            $res['psize']   = $psize;
            $res['count']   = $count;
        }

		e_json( $res );
	}

    //客户池导出模板
    public function _importTemplate()
    {
        $res = array('rcode'=>0,'msg'=>'500 Internal Error');
        $MExcel= new Excel();
        $PaySheet = new \Common\ORG\Sheet("对帐信息");
        $CustomerSheet = new \Common\ORG\Sheet("客户列表");
        $payData = $customerData = array();
        $payData['order'] = 'A0001';
        $payData['pay_time'] = date('Y/m/d');
        $payData['pay_name'] = '张三';
        $payData['customer_name'] = '张三';
        $payData['mount']  = '3680';
        $payData['pay_way'] = '天津支付宝';
        $payData['sales_person'] = '业务人员';
        $payData['sales_manager'] = '经理';
        $payData['team'] = '所属团队(郭勇\傅怀国\齐玉波\刘智华\张涵)';
        $payData['remark'] = '付款备注信息';
        $payData['audit_res'] = "已到帐";
        $payData['is_weigui'] = '否';
        $payData['order_number'] = '银行、支付宝、微信流水号';
        $PaySheet->setColumn(array_keys($this->m_payExcelKey));
        $PaySheet->addRow( array_values($payData) );
        $MExcel->add_sheet( $PaySheet );
        $customerData = array();
        $customerData['pay_order'] = '付款流水编号';
        $customerData['customer_name'] = '张三';
        $customerData['phone'] = '189xxxxxx';
        $customerData['weixin_id'] = '微信号 ';
        $customerData['customer_mount'] = '30(客户资金量，单位：万 )';
        $customerData['remark'] = '客户备注信息';
        $customerData['product'] = '购买产品';
        $customerData['mount'] = '合同金额与付款流水金额对应';
        $customerData['contract_time'] = '合同开始时间默认是付款时间';
        $customerData['service_time'] = '12(单位月)';
        $customerData['survey_code'] = 'FX4710170613364';
        $customerData['sales_person'] = '业务人员';
        $customerData['sales_manager'] = '业务人员经理';
        $customerData['addr'] = '客户详细地址信息';
        $customerData['revisit_time'] = '';
        $customerData['revisit_res'] = '';
        $customerData['revisit_remark'] = '';
        $p = array_flip($this->m_customerExcelKey);
        $p['addr'] = "地址\n金额小于1000元的只写手机号";
        $header = array();
        foreach($customerData as $vk=>$vu){
            $header[] = isset($p[$vk]) ? $p[$vk]:'';
        }
        $CustomerSheet->setColumn( $header );
        $CustomerSheet->addRow( array_values($customerData) );
        $MExcel->add_sheet( $CustomerSheet );
        $exportRet = $MExcel->export_sheet("客户数据", "导入数据.xls");
        if( $exportRet['rcode'] ){
            $res['rcode'] = 1;
            $res['data'] = $exportRet['data'];
            $res['msg'] = 'OK';
        }
        else
            $res['msg'] = $exportRet['msg'];
        e_json( $res );
    }

    //合并客户
    public function combine()
    {
        $res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'Intenal Error');
        if( IS_GET ){
            $res = array('success'=>true,'results'=>'');
            $param = I('get.q', '', 'trim');
            if( $param ){
                $MCu = D('Admin/Customer');
                $wheres = array();
                $wheres['c.state'] = array('not in', array( \Admin\Model\CustomerModel::STATE_COMBINE,
                    \Admin\Model\CustomerModel::STATE_INVALID_USER) );
                if( preg_match('#^\d{7,13}$#', $param )){
                    $MPhoneBook = D('Admin/CustomerPhonebook');
                    $wherep = array();
                    $wherep['book_phone'] = array('like','%'.$customer.'%');
                    $_arr_phones = $MPhoneBook->field("customer_id")->where( $wherep )->select();
                    $arr_phones = array();
                    foreach ($_arr_phones as $kp => $vp) {
                        $arr_phones[] = $vp['customer_id'];
                    }
                    if( !$arr_phones )
                        $arr_phones[] = 0;
                    $wheres['c.customer_id'] = array('in', $arr_phones );
                }
                else{
                    $wheres['c.nickname'] = array('like', '%'.$param.'%');
                }

                $findres= $MCu->alias("c")
                                  ->field("c.nickname as name,c.customer_id as value,c.phone as p")
                                  ->where( $wheres )
                                  ->limit("50")
                                  ->order("c.create_time desc")
                                  ->select();
                $res['results'] =  array();
                foreach ( $findres as $vf ) {
                    $item = array();
                    $item['name'] = $vf['name'].'-'.phone_mask( $vf['p'] );
                    $item['value'] = $vf['value'];
                    $res['results'][] = $item;
                }


            }
        }
        elseif ( IS_POST ) {
            $from = I('post.from', '', 'intval');
            $to = I('post.to', '', 'intval');
            $MService = D('Customer', 'Service', 'Admin');
            $dret = $MService->combineTo($from, $to );
            if( $dret['rcode'] ){
                $res['rcode'] = 1;
                $res['msg'] = 'OK';
            }
            else{
                $res['msg'] = $dret['msg'];
            }
        }

        e_json( $res );
    }

    //根据Exccl表格头的文案信息 匹配 列的位置
    private function _header_index( $_key, $_map, $_addr = FALSE /*匹配地址信息*/)
    {
        $match = array();
        if ($_key && $_map) {
            foreach ($_key as $kpd =>$vpd) {
                if ( isset($_map[$vpd]) )
                    $match[$_map[$vpd]] = $kpd;
                if ($_addr &&  !isset($match['addr']) && preg_match('#地址#is', $vpd )) {
                    $match['addr'] = $kpd;
                }
            }
        }

        return $match;
    }

    //根据KEY值获取Excel数据
    private function _row_data($_row, $_keys)
    {
        $nbArr = array('customer_name','pay_name','sales_person','sales_manager','team','phone','weixin_id');
        $row = array();
        $MExcel = new Excel();
        if ( $_row && $_keys ) {
            foreach ($_keys as $_k=>$_v) {
                $row[$_k] = isset($_row[$_v]) ? trim($_row[$_v]) : FALSE;
                //员工姓名、经理、部门、客户姓名中间空白的问题
                if ($row[$_k] && in_array($_k, $nbArr) ){
                    $row[$_k] = str_replace(' ','', $row[$_k]);
                }
            }
        }
        
        return $row;
    }

    //据业务人员、经理、团队、产品进行判断
    private function _row_valid( $_data )
    {
        $ret = array('rcode'=>0, 'msg'=>'', 'data'=>array('sales'=>false,'product'=>false, 'manager'=>false, 'team'=>false) );
        //增加合同时间判断是否正确
        $contract_start_time = isset($_data['contract_stime'])&&$_data['contract_stime'] ? strtotime($_data['contract_stime']):false;
        $tm3Month = strtotime("-3 months");
        if ($contract_start_time && $contract_start_time < $tm3Month){
            $contract_start_time = false;
        }
        if (!isset($_data['sales']) || !isset($_data['product']) || !isset($_data['manager']) || !isset($_data['team'])) {
            $ret['msg'] = "客户信息缺失";
        }
        else if (!isset($_data['survey_code']) || !$_data['survey_code']){
            $ret['msg'] = "风险问卷回执编号不能为空";
        }
        else if (!$contract_start_time){
            $ret['msg'] = "合同时间错误，只能导入三个月之内的数据";  
        }
        else {
            $_match = $this->_db_valid($_data['sales'], 'user');
            //后台员工不存在直接创建员工
            $MService = D('Admin/User','Service');
            if (!$_match) {
                $ret = $MService->addByTeam($_data['sales'], $_data['team']);
                if ($ret && $ret['rcode'])
                    $_match = $ret['data'];
            }

            if ($_match) {
                $ret['data']['sales'] = $_match;
                $_match = $this->_db_valid($_data['manager'], 'user');
                if ($_match) {
                    $ret['data']['manager'] = $_match;
                    $_match = $this->_db_valid($_data['product'], 'product');
                    if ($_match) {
                        $ret['data']['product'] = $_match;
                        $_match = $this->_db_valid($_data['team'], 'sector');
                        if ($_match) {
                            $ret['rcode'] = 1;
                            $ret['msg'] = 'OK';
                            $ret['data']['team'] = $_match;
                        }
                        else
                            $ret['msg'] = "团队不存在";
                    }
                    else
                        $ret['msg'] = "产品不存在";
                }
                else
                    $ret['msg'] = "团队经理不存在";
            }
            else
                $ret['msg'] = "业务人员不存在";
        }
        return $ret;
    }

    //处理失败记录
    private function _parse_error( $_data, $error )
    {
        $_data['error'] = $error;
        $_fusion = $_data;
        if (isset($_fusion['sub_user']))
            unset( $_fusion['sub_user']);
        $this->m_parseError[] = $_fusion;
        if ( isset($_data['sub_user'])&&$_data['sub_user'] ) {
            foreach ($_data['sub_user'] as $vf ) {
                $vf['error'] = $error;
                $this->m_parseError[] =$vf;
            }
        }
    }

    //查询数据库配置产品、销售、团队信息
    private function _db_valid( $_v, $_k)
    {
        $ret = false;
        $where = array();
        $_v = trim( $_v );
        if( !$_v )
            return $ret;
        if ('product' == $_k) {
            if (isset($this->m_cacheSearch[$_k][$_v] ))
                return $this->m_cacheSearch[$_k][$_v];
            else {
                $Mdo = D('Admin/Product');
                $where['name'] = array('eq', $_v );
                $ret = $Mdo->where( $where )->getField("product_id");
                if ($ret)
                    $this->m_cacheSearch[$_k][$_v] = $ret;
            }
        }
        else if ('sector'==$_k ){
            if (isset($this->m_cacheSearch[$_k][$_v] ))
                return $this->m_cacheSearch[$_k][$_v];
            else {
                $Mdo = D('Admin/Sector');
                $where['sector_name'] = array('eq', $_v );
                $ret = $Mdo->where( $where )->getField("sector_id");
                if ($ret)
                    $this->m_cacheSearch[$_k][$_v] = $ret;
            }
        }
        else if ('user'==$_k) {
            if (isset($this->m_cacheSearch[$_k][$_v] ))
                return $this->m_cacheSearch[$_k][$_v];
            else {
                $Mdo = D('Admin/User');
                $where['nickname'] = array('eq', $_v );
                $ret = $Mdo->field('user_id,sector_id')->where( $where )->find();
                if ($ret)
                    $this->m_cacheSearch[$_k][$_v] = $ret;
            }
        }
        return $ret;
    }


    /**
     * 客户查账流水导入
     *
     */
	public function pays_import()
    {
		$res = array('rcode'=>0,'data'=>NULL, 'msg'=> 'Intenal Error');
        //导入付款查账表格式验证,Excel表头独立处理与列位置无关
        $_payCKey = $this->m_payExcelKey;
        $_customerCKey = $this->m_customerExcelKey;

		if (IS_POST) {
			$act  = I('post.action', '', 'trim');
			$act = strtolower( $act );

			if ('upload' == $act) {
				$fname = I('post.name','file', 'trim');
	            $newDir = I('post.newname','','trim');
	            $Mdo = new AttUpload();
	            $MExcel = new Excel();
	            $realpath = '';
                //Excel文件上传
                $ret = $Mdo->http_upload( $fname, $newDir);
                if ($ret && (1 != $ret['rcode'])) {
                    $res['msg'] = $ret['msg'];
                    e_json( $res );
                }
                else
                    $realpath = $ret['data']['view_path'];

	            //Excel 解析
	            $excelData = $MExcel->parse_file(  $realpath );
	            if (!$excelData['rcode']) {
	            	$res['msg'] = $excelData['msg'];
	            	e_json( $res );
	            }

           		$parseData =  $excelData['data'];
                $payCKey = array();
                if ($parseData && isset($parseData['column']['s0'])) {
                    $payCKey  = $this->_header_index($parseData['column']['s0'], $_payCKey);
                }

                $clientKey = array();
                if ($parseData && isset( $parseData['column']['s1'] )) {
                    $clientKey  = $this->_header_index($parseData['column']['s1'], $_customerCKey, TRUE );
                }
           		if ( isset( $payCKey['order'] ) && isset( $payCKey['customer_name']) && isset( $clientKey['pay_order'] )  && isset( $clientKey['phone'] ) && isset( $clientKey['product'] ) ) {
           			$data = array('pays'=>array() ,'customers'=>array() );
           			$payItem = array();
           			foreach ($parseData['row']['s0'] as $vpay) {
                        $payItem = $this->_row_data($vpay, $payCKey);
                        $$payItem['is_weigui'] == $payItem['is_weigui']&&$payItem['is_weigui']=='是' ? true:false;
           				$data['pays'][$vpay['0']] = $payItem;
           			}

           			//筛选出需要合并的数据
					$filterData = $cuItem = array();
					$filterData['fusion'] = array();
					$filterData['down'] = array();
					$rows = array();
					$rowData = array();
           			foreach ($parseData['row']['s1'] as $vcu) {
                        $cuItem = $this->_row_data($vcu, $clientKey);
                        if (isset($cuItem['contract_mount']) && $cuItem['contract_mount'] )
           				    $cuItem['contract_mount'] =  doubleval( $cuItem['contract_mount'] );
                        if (isset($cuItem['customer_mount']) && $cuItem['customer_mount'] )
                            $cuItem['customer_mount'] =  doubleval( $cuItem['customer_mount'] );
                        $cuItem['sales_sub_company'] = $data['pays'][$cuItem['pay_order']]['team'];
           				$cuItem['pay'] = $data['pays'][$cuItem['pay_order']];
           				if (!$cuItem['contract_time'])
           					$cuItem['contract_time']  = $cuItem['pay']['pay_time'];
                        if (!$cuItem['contract_mount'])
                            $cuItem['contract_mount'] = doubleval($cuItem['mount']);
           				$key = md5( $cuItem['customer_name'].$cuItem['phone']);
           				$cuItem['key'] = $key;
                        //解析数据业务人员、经理、团队、产品进行判断
                        // 增加合同时间判断,开始时间
                        $vData = array('sales' => $cuItem['sales_person'], 'manager' => $cuItem['sales_manager'],
                                        'product' => $cuItem['product'], 'team' => $cuItem['sales_sub_company'],
                                        'survey_code' => $cuItem['survey_code'], 'contract_stime'=> $cuItem['contract_time']
                                        );
                        $vRet = $this->_row_valid( $vData );
                        if ($vRet&&1==$vRet['rcode']) {
                            $cuItem['_code'] = 1;
                            $cuItem['_msg'] = '';
                            $cuItem['_data'] = $vRet['data'];
                        }
                        else {
                            $cuItem['_code'] = 0;
                            $cuItem['_msg'] = $vRet['msg'];
                            $cuItem['_data'] = false;
                        }
           				$rows[] = $cuItem;
           				$rowData[$key] = isset($rowData[$key]) ? $rowData[$key]+1 : 1;
           			}

                    $fu_index = 0;
           			foreach ($rows as $vk => $vr) {
           				if ($rowData[$vr['key']] > 1) {
                            $vr['sub_user'] = array();
           					$filterData['fusion'][] = $vr;
                            $fu_index++;
                        }
           				else
           					$filterData['down'][] = $vr;
           			}

                    //按照名字、付款时间、合同金额进行排序
           			if ($filterData['fusion']) {
                        //客户资料按照最近时间排序
                        $fusionData =  $filterData['fusion'];
           				usort( $fusionData , function ( $a, $b) use( $order ) {
                            if ($a['key'] == $b['key']) {
                                $tm_s = strtotime( $a['contract_time'] );
                                $tm_e = strtotime( $b['contract_time'] );
                                if( $tm_e != $tm_s )  return ( $tm_s < $tm_e ) ? 1:-1;
                                return ( $a['contract_mount'] == $b['contract_mount'] ) ? 0:( ($a['contract_mount'] > $b['contract_mount'] ) ? 1:-1 );
                            }
                            else {
                                return (crc32($a['key']) > crc32($b['key'])) ? 1: -1;
                            }
                        });
                        $filterData['fusion'] = array();
                        $fusionData = array_reverse( $fusionData );
                        foreach ( $fusionData as $vindex=>$vd ) {
                            $vd['k'] = 'f'.$vindex;
                            $filterData['fusion'][$vd['k']] = $vd;
                        }
           			}
                    /*if ($filterData['down']) {
                        $downData = $filterData['down'];
                        $filterData['down'] = array();
                        foreach ( $downData as $vindex=>$vd ) {
                            $vd['k'] = 'd'.$vindex;
                            $filterData['down'][$vd['k']] = $vd;
                        }
                    }*/
           			$res['rcode'] = 1;
           			$res['msg'] = "OK";
           			$res['data'] = $filterData;
           		}
           		else {
           			$res['msg'] = "Excel表格上传格式错误";
                }

			}
			else if( 'save' == $act ){ //合并之后的数据进行保存
                /**
                 * BUG: php max_input_vars 不能输入更多参数，更改为json格式
                 * 
                */
                $data = isset( $_POST['data']) ? $_POST['data']:false;
                if ($data)
                    $data = json_decode($data, true);
                if ($data) {
                    $okCount = 0;
                    $errCount = array('customer'=>0,'pays'=>0);
                    $MCustomer = D('Customer','Service', 'Admin');
                    $data_fusion = isset($data['fusion']) ? (array)$data['fusion']:array();
                    $data_down = isset($data['down']) ? (array)$data['down']:array();
                    $savedata =  array_merge( $data_fusion, $data_down );
                    if ($savedata && count($savedata)) {
                        foreach ( $savedata as $fusion_k => $fusion_v ) {
                            if (0 == $fusion_v['_code']) {
                                $this->_parse_error($fusion_v, $fusion_v['_msg']);
                                continue;
                            }
                            //判断是否重复导入,根据付款时间以及序列号,或者订单号
                            $is_repeat = $MCustomer->oneExcelPay( $fusion_v['pay']['order'], $fusion_v['pay']['pay_time'],
                                                                            $fusion_v['pay_way'], $fusion_v['order_number']);
                            if ($is_repeat) {
                                $this->_parse_error($fusion_v, "重复导入");
                                continue;
                            }
                            $find = $MCustomer->findCount( $fusion_v['customer_name'], $fusion_v['sales_manager'] ,$fusion_v['phone'] );
                            $cid = 0;
                            /*当客户只提供姓名人时候默认创建客户*/
                            if (!$find || ( $find && $find['data'] == 1 )) {
                                if (!$find){
                                    $regRet = $MCustomer->register( $fusion_v );
                                    if( $regRet['rcode'] ){
                                        $cid = $regRet['data'];
                                    }
                                    else
                                        $this->_parse_error($fusion_v, $regRet['msg']);
                                }
                                else{
                                    $cid = $find['find']['customer_id'];
                                }
                                    
                                if ($cid) {
                                    //处理合同生成
                                    $mount = doubleval( $fusion_v['pay']['mount']);
                                    foreach ($fusion_v['sub_user'] as $vu) {
                                        $mount += doubleval( $vu['pay']['mount'] );
                                    }
                                    $ext = $fusion_v['_data'];
                                    $ext['pay'] = $fusion_v['pay'];
                                    $ext['survey_code'] = $fusion_v['survey_code'];
                                    $conid = $MCustomer->addContract( $cid, $mount, $fusion_v['contract_time'], $fusion_v['service_time'], $fusion_v['addr'], $ext);
                                    //根据回访情况更新是否需要回访
                                    if( '正常' == $fusion_v['revisit_res']){
                                        $MCustomer->updateContractVisit( $conid, 2 );
                                    }
                                    //处理付款记录
                                    $MCustomer->addPay($cid, $conid, $fusion_v['pay'], $fusion_v['_data']);
                                    $okCount++;
                                    foreach ($fusion_v['sub_user'] as $vu) {
                                        $vu['pay']['product'] = $vu['product'];
                                        $MCustomer->addPay($cid, $conid, $vu['pay'], $vu['_data']);
                                        $okCount++;
                                    }
                                }
                            }
                            else {
                                /*匹配到多个客户无法处理*/
                                $this->_parse_error($fusion_v, "匹配到多个客户，无法继续处理");
                            }
                        }
                        $res['rcode'] = 1;
                        $res['msg'] = 'OK';
                        $res['error'] = $errCount;
                        $res['ok'] = $okCount;
                        $res['data'] = $this->m_parseError;
                    }
                    else{
                        $res['msg'] = "上传数据失败";
                    }

                }
                else{
                    $res['msg'] = "参数提交错误";
                }

                //
			}

			e_json( $res );
		}
	}

    //客户详情浮层中显示数据
    public function getFloatInfos(){
       /*获取客户浮窗数据*/
        $res = array('rcode'=>0, 'data'=>NULL, 'msg'=> 'OK');
        $today = date('Y-m-d H:i:s');
        $customer_id = I('get.customer_id');
        $map = array();
        $map['combine_to'] = array('eq',$customer_id);
        $combinFromInfo = M('Customer')->field('customer_id')->where($map)->select();
        $v = count($combinFromInfo)+1;
        $combinFromInfo[$v]['customer_id'] = $customer_id;
        $combinFromInfo = array_reverse($combinFromInfo);
        foreach ($combinFromInfo as $ck => $cval) {
            $combinFromInfoD[] = intval($cval['customer_id']);
        }
        //客户信息
        $wheres1 = array();
        $wheres1['customer_id'] = array('eq',$customer_id);
        $customerInfo = M('customer')
                        ->field("customer_id,customer_code,nickname as customer_nickname,mount,remark")
                        ->where($wheres1)
                        ->find();
        //合同信息
        $wheres2 = array();
        $wheres2['contract.customer_id'] = array('in',$combinFromInfoD);
        $wheres2['contract.state'] = array('in',[1,3]);
        $contractInfo = M('contract')
                    ->field('p.name as productName,contract.start_time,contract.end_time,
                    contract.state,contract.contract_id,contract.customer_id,contract.create_time')
                    ->join("LEFT JOIN product p on p.product_id=contract.product_id")
                    ->where($wheres2)
                    ->order("contract.create_time desc,contract.contract_id")
                    ->select();
        $servicedDay = 0;
        $servicedTimeAll = 0;
        $servicedTime = 0;
        $noservicedTime = 0;
        $onServiceContrCount = 0;
        for ($j=0; $j < count($contractInfo); $j++) {
            //合同剩余时间
            $contractInfo[$j]['remainDays'] = D('Customer')->diffBetweenTwoDays($contractInfo[$j]['end_time'],date('Y-m-d H:i:s'));
            //计算累加服务时长
            $contractInfoNeed[$j] = $contractInfo[$j];
            //计算合同付款金额
            $wheres4[$j] = array();
            $wheres4[$j]['contract_id'] = array('eq',$contractInfo[$j]['contract_id']);
            $payMount[$j] = M('pay_record')->field('sum(pay_mount) as paymount')->where($wheres4[$j])->find();
            $contractInfo[$j]['paymount'] = $payMount[$j]['paymount'];
            //去掉合同付款金额后面的'.00'
            if($contractInfo[$j]['paymount'] && substr($contractInfo[$j]['paymount'], -3) == '.00'){
                $contractInfo[$j]['paymount'] = floor($contractInfo[$j]['paymount']);
            }
            if($contractInfo[$j]['end_time'])
                $contractInfo[$j]['end_time'] = substr($contractInfo[$j]['end_time'],0,10);
            //计算服务中合同数
            if($contractInfo[$j]['state'] == 1){
                $onServiceContr[] = $contractInfo[$j];
                $onServiceContrCount++;
            }
        }
        for ($m=0; $m < count($onServiceContr); $m++) {
            if($m<2)    //服务中心合同最多显示2条数据
                $contractInfoTwo[$m] = $onServiceContr[$m];
        }
        //计算累加服务时长
        foreach ($contractInfoNeed as $key => $row) {
            $start_time[$key]  = $row['start_time'];
        }
        array_multisort($start_time, SORT_ASC, $contractInfoNeed); //排序
        if($contractInfoNeed){
            $servicedTimeAll = (strtotime($today)-strtotime($contractInfoNeed[0]['start_time']));  //计算最早签订合同到现在时间差
            for ($m=0; $m < count($contractInfoNeed); $m++) {   //签订合同期间完成的合同，不计入统计中
                if($contractInfoNeed[$m]['start_time']>=$contractInfoNeed[$m-1]['start_time'] && $contractInfoNeed[$m]['end_time']<=$contractInfoNeed[$m-1]['end_time'])
                    unset($contractInfoNeed[$m]);
                $contractInfoNeed = array_values($contractInfoNeed);
            }
            for ($n=1; $n < count($contractInfoNeed); $n++) {   //两个合同间隔时间差
                if($contractInfoNeed[$n]['start_time']>$contractInfoNeed[$n-1]['end_time']){
                    $noservicedTime += (strtotime($contractInfoNeed[$n-1]['end_time'])-strtotime($contractInfoNeed[$n]['start_time']));
                }
            }
            $servicedTime = $servicedTimeAll+$noservicedTime;
        }
        $servicedDay = intval($servicedTime / (24*3600));   //累加服务时长
        //投诉次数
        $wheres3 = array();
        $wheres3['customer_id'] = array('in',$combinFromInfoD);
        $wheres3['incoming_type'] = array('eq',31); //400来电类型为投诉
        $wheres3['is_delete'] = array('neq',1);
        $complainCount = M('Customer_complain')->where($wheres3)->count();
        if($customer_id){
            if($customerInfo){
                $res['rcode'] = 1;
                $res['customerInfo'] = $customerInfo;   //客户信息
                $res['servicedDay'] = $servicedDay; //计算累加服务时长
                $res['contractInfo'] = $contractInfo;   //合同信息
                $res['complainCount'] = $complainCount;     //投诉次数
                $res['combinFromInfoD'] = $combinFromInfoD;
                $res['contractCount'] = $onServiceContrCount;
                $res['contractInfoTwo'] = count($contractInfoTwo);
                if(count($contractInfo)>2)
                    $res['contractInfo'] = $contractInfoTwo;
            }
        }else{
            $res['msg'] = '获取参数错误！';
        }
        e_json($res);
    }



}
